from django.db import transaction
from rest_framework import serializers
from .models import *
from django.db.utils import IntegrityError
from django.db.models import F

class ProductPicSerializer(serializers.ModelSerializer):
    class Meta:
        model=ProductPic
        exclude='product',

class ProductStyleSerializer(serializers.ModelSerializer):
    class Meta:
        model=ProductStyle
        exclude='product',

class ProductSerializer(serializers.ModelSerializer):
    gender=serializers.SerializerMethodField()
    type = serializers.SerializerMethodField()
    category = serializers.SerializerMethodField()
    pic = ProductPicSerializer(many=True,label='图片列表')
    style=ProductStyleSerializer(many=True,label='款式列表')
    size=serializers.SerializerMethodField()
    class Meta:
        model=Product
        fields='__all__'
    def get_gender(self,obj):
        return obj.get_gender_display()
    def get_type(self,obj):
        return obj.get_type_display()
    def get_category(self,obj):
        return obj.category.title
    def get_size(self,obj):
        size=[]
        if obj.size:
            size=obj.size.split('|')
        return size


class ShopCartSerializer(serializers.ModelSerializer):
    class Meta:
        model=ShopCart
        exclude='user',


    def save(self, **kwargs):
        request = self.context['request']
        self.validated_data['user'] =request.user
        try:
            obj=super().save(**kwargs)
        except IntegrityError:
            obj=ShopCart.objects.get(
                user=self.validated_data['user'],
                product=self.validated_data['product'],
                style = self.validated_data['style'],
                size = self.validated_data['size'],
            )
            obj.count +=self.validated_data['count']
            obj.save()
        return obj

class ShopOrderSerializer(serializers.ModelSerializer):
    item_list = serializers.PrimaryKeyRelatedField(
        label="购物车条目的id列表", many=True, allow_empty=False,
        queryset=ShopCart.objects.all()
    )

    voucher = serializers.PrimaryKeyRelatedField(
        label="代金券id", allow_empty=True,required=False,
        queryset=Voucher.objects.all()
    )

    class Meta:
        model = ShopOrder
        exclude = ("user",)


    @transaction.atomic() # 事务打包
    def save(self, **kwargs):
        request = self.context['request']
        self.validated_data['user'] = request.user
        item_list = self.validated_data.pop("item_list")
        voucher = self.validated_data.pop("voucher",None)

        if voucher and not voucher.can_use():
            raise serializers.ValidationError('代金券不可以')
        obj = super().save(**kwargs)

        _item_list = []
        for item in item_list:
            if item.count > item.product.stock:  # 购买数量大于库存
                raise serializers.ValidationError(f'该商品库存不足:product_id={item.product.id}')
            else:
                # item.product.stock=F("stock") - item.count   ##mysql
                item.product.stock-=item.count                 ##sqllite
                item.product.save()
                item.product.refresh_from_db()
                item.product.full_clean()
            _item_list.append(ShopItem.objects.create(
                order=obj,
                style=item.style,
                size=item.size,
                count=item.count,
                price=item.product.sales_price,
            ))
        # 删除购物车买过的商品
        # for item in item_list:
        #     item.delete()
        # 统计订单价格
        obj.amount=sum([_item.count * _item.price for _item in _item_list])
        obj.pay_amount=obj.amount
        obj.save()
        if voucher and voucher.can_use():
            voucher.use(obj)

        ShopCart.objects.filter(id__in=[_.id for _ in item_list]).delete()

        return obj


class ShopOrderOutSerializer(ShopOrderSerializer):
    item_list = None
    voucher = None



